package com.wing.api.add.productDetail.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wing.api.ApplicationContextUtil;
import com.wing.api.add.productDetail.BaseProductDetailSeriesService;
import com.wing.cabinet.model.response.EnterpricceIdVO;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.entity.Product;
import com.wing.product.model.request.ProductForm;
import com.wing.product.service.MostUsedKnifeListServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * 标准部门接口
 */
@Service
@Slf4j
public class StandardProductDetailServiceImpl implements BaseProductDetailSeriesService {

    @Transactional
    @Override
    public void logicProcess(JSONObject jsonObject, EnterpricceIdVO enterpricceIdVo) throws IOException {
        log.info("请求参数,{}", jsonObject.toJSONString());
        //此处需要做接口签名验证
        //sign = md5（参数1+参数2+参数3+key）
        String sourceSign = jsonObject.getString("sign"); // 签名值
        JSONArray data = jsonObject.getJSONArray("data"); //业务数据
        if(StringUtils.isBlank(sourceSign)){
            throw new BusinessException("签名值为空！");
        }
        if(StringUtils.isBlank(data.toJSONString())){
            throw new BusinessException("请求参数为空！");
        }
        /*log.info("签名源串,{}", sourceSign);
        String desSign = DigestUtil.md5Hex("productName" + "skuName" + "skuCode" + "marketPrice" + enterpricceIdVo.getKey());
        log.info("签名目的串,{}", desSign);
        if(!desSign.equals(sourceSign)){
            throw new BusinessException("签名不通过！");
        }*/

        StringBuffer tempStr = new StringBuffer();
        tempStr.append(data);
        tempStr.append(enterpricceIdVo.getKey());
        log.info("签名源串,{}", sourceSign);
        String desSign = DigestUtil.md5Hex(tempStr.toString());
        log.info("签名目的串,{}", desSign);
        if(!desSign.equals(sourceSign)){
            throw new BusinessException("签名不通过！");
        }
        EnterpriseClient enterpriseClient = (EnterpriseClient) ApplicationContextUtil.getBean("enterpriseClientFallback");
        //业务逻辑
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObj = data.getJSONObject(i);
            String productName = jsonObj.getString("productName");
            if(StringUtils.isEmpty("productName")){
                throw new BusinessException("第" + (i+1) +  "规格系列不能为空！");
            }
            JsonResult<Product> productJsonResult = enterpriseClient.getProductByName(productName);
            if(productJsonResult.getData().getId() == null){
                throw new BusinessException("第" + (i+1) +"当前规格系列不存在，请先同步规格系列数据！");
            }

            String skuName = jsonObj.getString("skuName");
            if(StringUtils.isEmpty(skuName)){
                throw new BusinessException("第" + (i+1) +  "行物料名称不能为空！");
            }
            String skuCode = jsonObj.getString("skuCode");
            if(StringUtils.isEmpty(skuCode)){
                throw new BusinessException("第" + (i+1) +  "行物料编号不能为空！");
            }
            MostUsedKnifeListServiceImpl mostUsedKnifeListServiceImpl = (MostUsedKnifeListServiceImpl) ApplicationContextUtil.getBean("mostUsedKnifeListServiceImpl");
            JsonResult onlyCode = mostUsedKnifeListServiceImpl.isOnlyCode(skuCode, null);
            if("false".equals(onlyCode.getData().toString())){
                throw new BusinessException("第" + (i+1) +"行物料编号必须唯一，该编号：" +skuCode+ "已存在！");
            }
            String marketPrice = jsonObj.getString("marketPrice");
            if(StringUtils.isEmpty(marketPrice)){
                throw new BusinessException("第" + (i+1) +  "行价格不能为空！");
            }
            String inventoryUnitType = jsonObj.getString("inventoryUnitType");
            String returnType = jsonObj.getString("returnType");
            ProductForm productForm = new ProductForm();
            productForm.setBrandId(0l);
            productForm.setProductId(productJsonResult.getData().getId());
            productForm.setSkuCode(skuCode);
            productForm.setName(skuName);
            productForm.setMarketPrice(new BigDecimal(marketPrice));
            productForm.setBrandId(0l);
            productForm.setSkuSpecValueNames(productJsonResult.getData().getSpecCode());
            if(productJsonResult.getData().getProductCategoryId()!=null){
                productForm.setProductCategoryId(productJsonResult.getData().getProductCategoryId());
            }else{
                productForm.setProductCategoryId(0l);
            }
           if(productJsonResult.getData().getProductTypeId()!=null){
               productForm.setProductTypeId(productJsonResult.getData().getProductTypeId());
           }else{
               productForm.setProductTypeId(0l);
           }

            if(StringUtils.isEmpty(inventoryUnitType)){
                productForm.setInventoryUnitType(inventoryUnitType);
            }
            if(StringUtils.isEmpty(returnType)){
                productForm.setReturnType(Boolean.parseBoolean(returnType));
            }

            mostUsedKnifeListServiceImpl.addCompactProduct(productForm);


        }
    }
    public static void main(String[] args) {
        String desSign = DigestUtil.md5Hex("123456");
        String desSign2= DigestUtil.md5Hex("productName" + "skuName" + "skuCode" + "marketPrice"+ desSign);
        System.out.println(desSign);
        System.out.println(desSign2);
    }
}
